package com.heoller.service.generator;

import com.heoller.dto.CustomParam;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author huliang
 * @date 2021-11-23 15:40
 */
@Service
public class GeneratorService {

    @Value("#{'${generator.module.list}'.split(',')}")
    private List<String> modules;

    private ModuleGeneratorService moduleGeneratorService;

    @Autowired
    public void setModuleGeneratorService(ModuleGeneratorService moduleGeneratorService) {
        this.moduleGeneratorService = moduleGeneratorService;
    }

    public byte[] generate(CustomParam customParam) {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ZipOutputStream zip = new ZipOutputStream(outputStream)) {
            moduleGeneratorService.generateRoot(zip, customParam);
            // 遍历需要创建的模块
            for (String module : modules) {
                moduleGeneratorService.generate(zip, module, customParam);
            }
            IOUtils.closeQuietly(zip);
            return outputStream.toByteArray();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return new byte[]{};
    }
}
